using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

namespace TuDouUnity.UI
{
    public class SettingsPanel : MonoBehaviour
    {
        [Header("UI References")]
        [SerializeField] private Slider masterVolumeSlider;
        [SerializeField] private Slider musicVolumeSlider;
        [SerializeField] private Slider sfxVolumeSlider;
        [SerializeField] private Dropdown resolutionDropdown;
        [SerializeField] private Button closeButton;

        private const string MASTER_VOLUME_KEY = "MasterVolume";
        private const string MUSIC_VOLUME_KEY = "MusicVolume";
        private const string SFX_VOLUME_KEY = "SFXVolume";
        private const string RESOLUTION_INDEX_KEY = "ResolutionIndex";
        private const float DEFAULT_VOLUME = 0.7f;

        private Resolution[] resolutions;

        private void Start()
        {
            InitializeResolutionDropdown();
            
            // 加载保存的音量设置
            masterVolumeSlider.value = PlayerPrefs.GetFloat(MASTER_VOLUME_KEY, DEFAULT_VOLUME);
            musicVolumeSlider.value = PlayerPrefs.GetFloat(MUSIC_VOLUME_KEY, DEFAULT_VOLUME);
            sfxVolumeSlider.value = PlayerPrefs.GetFloat(SFX_VOLUME_KEY, DEFAULT_VOLUME);

            // 添加监听器
            masterVolumeSlider.onValueChanged.AddListener(SetMasterVolume);
            musicVolumeSlider.onValueChanged.AddListener(SetMusicVolume);
            sfxVolumeSlider.onValueChanged.AddListener(SetSFXVolume);
            resolutionDropdown.onValueChanged.AddListener(SetResolution);
            closeButton.onClick.AddListener(CloseSettings);

            // 应用初始音量设置
            SetMasterVolume(masterVolumeSlider.value);
            SetMusicVolume(musicVolumeSlider.value);
            SetSFXVolume(sfxVolumeSlider.value);
        }

        private void InitializeResolutionDropdown()
        {
            // 获取所有可用分辨率
            resolutions = Screen.resolutions;
            resolutionDropdown.ClearOptions();

            // 创建分辨率选项列表
            List<string> options = new List<string>();
            int currentResolutionIndex = 0;

            for (int i = 0; i < resolutions.Length; i++)
            {
                string option = $"{resolutions[i].width} x {resolutions[i].height}";
                options.Add(option);

                // 检查是否是当前分辨率
                if (resolutions[i].width == Screen.currentResolution.width &&
                    resolutions[i].height == Screen.currentResolution.height)
                {
                    currentResolutionIndex = i;
                }
            }

            resolutionDropdown.AddOptions(options);
            
            // 加载保存的分辨率设置或使用当前分辨率
            int savedResolutionIndex = PlayerPrefs.GetInt(RESOLUTION_INDEX_KEY, currentResolutionIndex);
            if (savedResolutionIndex < resolutions.Length)
            {
                resolutionDropdown.value = savedResolutionIndex;
                SetResolution(savedResolutionIndex);
            }
            else
            {
                resolutionDropdown.value = currentResolutionIndex;
                SetResolution(currentResolutionIndex);
            }
        }

        public void SetResolution(int resolutionIndex)
        {
            if (resolutionIndex >= 0 && resolutionIndex < resolutions.Length)
            {
                Resolution resolution = resolutions[resolutionIndex];
                Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
                PlayerPrefs.SetInt(RESOLUTION_INDEX_KEY, resolutionIndex);
            }
        }

        public void SetMasterVolume(float volume)
        {
            PlayerPrefs.SetFloat(MASTER_VOLUME_KEY, volume);
            AudioListener.volume = volume;
        }

        public void SetMusicVolume(float volume)
        {
            PlayerPrefs.SetFloat(MUSIC_VOLUME_KEY, volume);
            // 查找背景音乐的AudioSource并设置音量
            var bgm = GameObject.Find("BackgroundMusic")?.GetComponent<AudioSource>();
            if (bgm != null)
            {
                bgm.enabled = true;
                bgm.volume = volume;
            }
        }

        public void SetSFXVolume(float volume)
        {
            PlayerPrefs.SetFloat(SFX_VOLUME_KEY, volume);
            
            // 获取GameManager实例
            GameManager gameManager = GameManager.Instance;
            if (gameManager != null)
            {
                // 设置所有音效的音量
                SetAudioSourceVolume(gameManager.attackMusic, volume);
                //SetAudioSourceVolume(gameManager.shootMusic, volume);
                SetAudioSourceVolume(gameManager.menuMusic, volume);
                SetAudioSourceVolume(gameManager.hurtMusic, volume);
                
                // 播放一个随机音效作为测试
                PlayRandomTestSound(gameManager);
            }
        }

        private void SetAudioSourceVolume(GameObject audioObject, float volume)
        {
            if (audioObject != null)
            {
                var audioSource = audioObject.GetComponent<AudioSource>();
                if (audioSource != null)
                {
                    audioSource.enabled = true;
                    audioSource.volume = volume;
                }
            }
        }

        private void PlayRandomTestSound(GameManager gameManager)
        {
            // 随机选择一个音效播放
            GameObject[] sounds = { 
                gameManager.attackMusic, 
                gameManager.shootMusic, 
                gameManager.hurtMusic 
            };

            int randomIndex = Random.Range(0, sounds.Length);
            var audioSource = sounds[randomIndex]?.GetComponent<AudioSource>();
            if (audioSource != null && !audioSource.isPlaying)
            {
                audioSource.enabled = true;
                audioSource.Play();
            }
        }

        public void CloseSettings()
        {
            // 播放菜单音效
            var menuAudio = GameManager.Instance?.menuMusic?.GetComponent<AudioSource>();
            if (menuAudio != null)
            {
                menuAudio.enabled = true;
                menuAudio.Play();
            }
            
            gameObject.SetActive(false);
        }
    }
} 